<?php

namespace app\common\customer\logic;

use app\common\BaseLogic;
use app\common\customer\model\CustomerAllocate;
use app\common\customer\model\CustomerInvite;
use app\common\order\model\OrderBom;
use app\common\system\logic\DepartmentLogic;
use app\common\system\logic\UserLogic;

class AllocateLogic extends BaseLogic
{
    public function getAllocate($memberId, $userId, $fields = "*")
    {
        $cacheName = "member:allocate:{$memberId}:{$userId}";

        if ($fields == "*") {
            $data = $this->redis->hGetAll($cacheName);
        } else {
            $data = $this->redis->hMGet($cacheName, $fields);
        }

        if (empty($data['id'])) {
            $model = new CustomerAllocate();
            $row = $model->where('member_id', $memberId)->where('create_id', $userId)->find();
            if (!empty($row)) {
                $data = $row->getData();
                $this->redis->hMSet($cacheName, $data);
                if ($fields != "*") $data = array_search_keys($data, $fields);
            } else {
                $data = [];
            }
        }

        return $data;
    }

    public function resetAllocateCache($memberId, $userId)
    {
        $cacheName = "member:allocate:{$memberId}:{$userId}";
        $this->redis->del($cacheName);
    }

    // 统计
    public function statistics($userIds, $dateRange)
    {

        // 获取要统计的状态
        $setup = config();
        $arr = $setup['app']['statistics_status'];
        $status = array_keys($arr);

        $model = new CustomerAllocate();
        $where = [];
        $where[] = ['user_id', 'in', $userIds];
        $where[] = ['status', 'in', $status];
        $where[] = ['create_time', 'between', $dateRange];
        $rows = $model->where($where)->field('status, count(id) as total')->group('status')->select();
        $map = [];
        foreach ($rows as $row) {
            $map[$row['status']] = $row['total'];
        }

        // 返回数据
        $data = [];
        foreach ($arr as $key => $value) {
            $data[] = [
                'status' => $key,
                'title' => $value,
                'total' => $map[$key] ?? 0
            ];
        }

        // 客资总数
        $data[] = [
            'status' => 0,
            'title' => '总进店',
            'total' => $model->where('user_id', 'in', $userIds)->where('create_time', 'between', $dateRange)->count()
        ];

        // 进店总数
        $model = new CustomerInvite();
        $invite = $model->where('create_id|user_id', 'in', $userIds)->where('invite_time', 'between', $dateRange)->count();
        $data[] = [
            'status' => -1,
            'title' => '进店',
            'total' => $invite
        ];
        return $data;
    }

    /**
     * 客资签约
     * 订单数 = 订单数
     * 签约金额 = 订单签约金额合计
     * 签约率 = 个人接收了多少咨询，产生的订单（小明接了10个咨询，定了一个，签约率=10%）
     * 门店签约总数 = 单个门店签约总单数（西郊店本周订单10个）
     * 门店签约率 = 门店本周接收了100个咨询。订单20单。（20%签约率）
     * @param $userIds
     * @param $storeIds
     * @param $dateRange
     * @return array
     */
    public function roi($user, $userIds, $storeIds, $dateRange)
    {
        $model = new CustomerAllocate();
        // 个人接待总数
        $where = [];
        $where[] = ['user_id', '=', $user['id']];
        $where[] = ['create_time', 'between', $dateRange];
        $staffMemberTotals = $model->where($where)->count();

        // 门店接待总数
        $where = [];
        $where[] = ['user_id', 'in', $userIds];
        $where[] = ['create_time', 'between', $dateRange];
        $storeMemberTotals = $model->where($where)->count();
        

        $model = new OrderBom();
        $where = [];
        if ($user['user_type'] == 1) {
            // 个人签约 
            $where[] = ['user_id', 'in', $userIds];
        } else {
            // 门店签约
            $where[] = ['store_id', 'in', $storeIds];
        }
        $where[] = ['sign_date', 'between', $dateRange];
        // 个人签约总数
        $staffSignAmount = $model->where($where)->count();
        
        // 个人签约金额
        $staffSignTotals = $model->where($where)->sum('totals');
        // 门店签约总数
        $where = [];
        $where[] = ['store_id', 'in', $storeIds];
        $where[] = ['sign_date', 'between', $dateRange];
        $storeSignAmount = $model->where($where)->count();

        return [
            [
                'title' => '订单数',
                'total' => $staffSignAmount,
            ],
            [
                'title' => '签约金额',
                'total' => $staffSignTotals,
            ],
            [
                'title' => '签约率',
                'total' => $staffMemberTotals > 0 ? round($staffSignAmount / $staffMemberTotals * 100, 2) : 0,
            ],
            [
                'title' => '门店签约总数',
                'total' => $storeSignAmount,
            ],
            [
                'title' => '门店签约率',
                'total' => $storeMemberTotals > 0 ? round($storeSignAmount / $storeMemberTotals * 100, 2) : 0,
            ]
        ];
    }

    // 部门平均分配
    public function department($memberId)
    {

    }

    // 组员间平均分配
    public function staff()
    {

    }
}